package com.mmall.Concurrency.example.atomic;



import com.mmall.Concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Target;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ThreadSafe
public class AtomicExample6 {

    private static AtomicBoolean isHappend = new AtomicBoolean(false);

    private static int ClinetTotal = 1000;
    private static int ThreadTotal = 20;
    private static AtomicInteger Count = new AtomicInteger(0);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(ThreadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(ClinetTotal);
        for (int i = 0; i < ClinetTotal; i++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                   add();
                   if(isHappend.compareAndSet(false,true));
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
            executorService.shutdown();
            log.info("count", Count.get());
            log.info(isHappend.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    public static void add(){
        Count.incrementAndGet();
    }
}

